#include <common.h>
#include <dm.h>
#include <dm/lists.h>
#include <dm/uclass-internal.h>
#include <log.h>
#include <errno.h>
#include <asm/gpio.h>
#include <beeper.h>

struct beeper_gpio_priv {
	struct gpio_desc gpio;
    bool		  beeping;
};

static int gpio_beeper_set_state(struct udevice *dev, enum beeper_state_t state)
{
	struct beeper_gpio_priv *priv = dev_get_priv(dev);
	int ret;

	if (!dm_gpio_is_valid(&priv->gpio))
		return -EREMOTEIO;
	switch (state) {
        case BEEPER_OFF:
        case BEEPER_ON:
            break;
        case BEEPER_TOGGLE:
            ret = dm_gpio_get_value(&priv->gpio);
            if (ret < 0)
                return ret;
            state = !ret;
            break;
        default:
            return -ENOSYS;
	}

	return dm_gpio_set_value(&priv->gpio, state);
}

static enum beeper_state_t gpio_beeper_get_state(struct udevice *dev)
{
	struct beeper_gpio_priv *priv = dev_get_priv(dev);
	int ret;

	if (!dm_gpio_is_valid(&priv->gpio))
		return -EREMOTEIO;
	ret = dm_gpio_get_value(&priv->gpio);
	if (ret < 0)
		return ret;

	return ret ? BEEPER_ON : BEEPER_OFF;
}

static int beeper_gpio_probe(struct udevice *dev)
{
    struct beeper_uc_plat *uc_plat = dev_get_uclass_plat(dev);
	struct beeper_gpio_priv *beeper_priv = dev_get_priv(dev);
    int ret;

	/* Ignore the top-level button node */
	if (!uc_plat->label)
		return 0;
    
    return gpio_request_by_name(dev, "gpios", 0, &priv->gpio, GPIOD_IS_OUT);
}

static int button_gpio_remove(struct udevice *dev)
{
	/*
	 * The GPIO driver may have already been removed. We will need to
	 * address this more generally.
	 */
	if (!IS_ENABLED(CONFIG_SANDBOX)) {
		struct beeper_gpio_priv *priv = dev_get_priv(dev);

		if (dm_gpio_is_valid(&priv->gpio))
			dm_gpio_free(dev, &priv->gpio);
	}

	return 0;
}

static int beeper_gpio_bind(struct udevice *parent)
{
	struct udevice *dev;
	ofnode node;
	int ret;

	dev_for_each_subnode(node, parent) {
		struct beeper_uc_plat *uc_plat;
		const char *label;

		label = ofnode_read_string(node, "label");
		if (!label) {
			debug("%s: node %s has no label\n", __func__, ofnode_get_name(node));
			return -EINVAL;
		}
		ret = device_bind_driver_to_node(parent, "beeper_gpio", ofnode_get_name(node), node, &dev);
		if (ret)
			return ret;
		uc_plat = dev_get_uclass_plat(dev);
		uc_plat->label = label;
	}

	return 0;
}


static const struct udevice_id beeper_gpio_ids[] = {
	{ .compatible = "gpio-beeper" },
	{ }
};

static const struct beeper_ops beeper_gpio_ops = {
	.set_state	= gpio_beeper_set_state,
	.get_state	= gpio_beeper_get_state,
};


U_BOOT_DRIVER(beeper_gpio) = {
	.name	= "beeper_gpio",
	.id	= UCLASS_BEEPER,
	.of_match = beeper_gpio_ids,
    .ops		= &beeper_gpio_ops,
	.bind	= beeper_gpio_bind,
	.probe		= beeper_gpio_probe,
	.remove		= beeper_gpio_remove,
};